package com.tj.jinzao.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.tj.jinzao.R;


/**
 * Toast统一管理类
 * created by wjy 2015/11/2
 */
public class ToastUtils {
    private static Toast sToast;

    private ToastUtils() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    public static void showToast(Context context, int resId, int duration, int gravity) {
        showToast(context, context.getString(resId), duration, gravity);
    }

    public static void showToast(final Context context, final String text) {
        showToast(context, text, Toast.LENGTH_SHORT, Gravity.CENTER);
    }

    public static void showToast(Context context, int resId) {
        showToast(context, resId, Toast.LENGTH_SHORT, Gravity.CENTER);
    }

    public static void showToast(final Context context, final String text, final int duration, final int gravity) {
        if (TextUtils.isEmpty(text) || context == null) {
            return;
        }
        try {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        Toast toast = getToast(context, gravity, duration);
                        setText(text);
                        toast.show();
                    } catch (Exception e) {
                    }
                }
            };
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(runnable);
        } catch (Exception e) {
        }
    }

    private static Toast getToast(Context context, int gravity, int duration) {
//        if (null == sToast) {
        try {
            LayoutInflater inflater = LayoutInflater.from(context);
            final View layout = inflater.inflate((R.layout.toast_layout), null);
            sToast = new Toast(context);
            sToast.setGravity(Gravity.CENTER, 0, context.getResources().getDisplayMetrics().heightPixels / 5);
            sToast.setDuration(duration);
            sToast.setView(layout);
        } catch (Exception e) {
        }
//        }
        if (sToast != null && gravity != sToast.getGravity()) {
            sToast.setGravity(gravity, 0, gravity == Gravity.CENTER
                    ? context.getResources().getDisplayMetrics().heightPixels / 5 : 0);
        }
        return sToast;
    }

    private static Toast setText(String text) {
        if (null != sToast) {
            try {
                View layout = sToast.getView();
                TextView textView = (TextView) layout.findViewById(R.id.ToastText);
                textView.setText(text);
            } catch (Exception e) {
            }
        }
        return sToast;
    }

}